package com.lyj.security.interceptor;

import cn.hutool.core.util.StrUtil;
import com.lyj.common.core.constants.Constants;
import com.lyj.common.core.constants.HttpConstants;
import com.lyj.common.core.utils.ThreadLocalUtil;
import com.lyj.security.service.TokenService;
import io.jsonwebtoken.Claims;
import jakarta.servlet.http.HttpServletRequest;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Component;
import org.springframework.web.servlet.HandlerInterceptor;

/**
 * Created with IntelliJ IDEA.
 * Description:
 * User: LIUYANJIAO
 * Date: 2025-08-13
 * Time: 23:47
 */
@Component
public class TokenInterceptor implements HandlerInterceptor {
    @Autowired
    private TokenService tokenService;

    @Value("${jwt.secret}")
    private String secret;
    @Override
    public boolean preHandle(jakarta.servlet.http.HttpServletRequest request, jakarta.servlet.http.HttpServletResponse response, Object handler) throws Exception {
        //从请求头中拿到token
        String token = getToken(request);
        if(StrUtil.isEmpty(token)){
            return true;
        }
        Claims claims = tokenService.getClaims(token,secret);
        String userKey = tokenService.getUserKey(claims);
        ThreadLocalUtil.set(Constants.USER_KEY,userKey);
        tokenService.extendToken(claims);
        return true;
    }

    @Override
    public void afterCompletion(jakarta.servlet.http.HttpServletRequest request, jakarta.servlet.http.HttpServletResponse response, Object handler, Exception ex) throws Exception {
        ThreadLocalUtil.remove();
    }
    private String getToken (HttpServletRequest httpServletRequest){
        String token = httpServletRequest.getHeader(HttpConstants.AUTHENTICATION);
        if(StrUtil.isNotEmpty(token) && token.startsWith(HttpConstants.PREFIX)){
            token = token.replaceFirst(HttpConstants.PREFIX,"");
        }
        return token;
    }
}
